import React, {Component} from 'react';
import {Button, Form, Input, Upload, Icon, message, InputNumber} from "antd";
import {axiosPostFunction, baseUrl, parseToJsonObj} from "../MyConfig/AppConfig";
import {file} from "@topology/core/src/middles/nodes/file";

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

class NewLogicComponentForm extends Component {

    state = {
        logic_component_id: -1,
        img_url: null,
        file_path: null,
        loading: false,
        user_id: -1,
    }

    componentDidMount() {
        let user_id_str = localStorage.getItem("userInfo:id");
        this.setState({
            user_id: parseInt(user_id_str, 10),
        })
    }

    // 点击【提交】按钮之后的函数
    onClickSubmit = (event) => {
        event.preventDefault();
        let form_obj = this.props.form;
        form_obj.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log("表单收到数据：", values);
                axiosPostFunction(
                    "/logic_component/new",
                    {
                        ...values,
                        img_url: this.state.img_url,
                        logic_component_id: this.state.logic_component_id,
                        author_id: parseInt(localStorage.getItem("userInfo:id"),10),
                        file_path: this.state.file_path,
                    },
                    (received_data)=>{
                        let { logic_component_id } = received_data;
                        if (logic_component_id && logic_component_id > 0){
                            message.success("添加成功");
                            setTimeout(()=>{
                                // 重置表单
                                this.props.form.resetFields();
                                this.setState({ img_url: null })
                            }, 800)
                        }else {
                            message.error("添加失败")
                        }
                    },
                    ()=>{
                        message.error("上传失败")
                    })
            }
        });
    }

    // 文件上传前的验证操作
    beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 文件');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图像大小应该小于 2MB');
        }
        return false;
    }

    // 处理文件上传过程中的状态变化
    handleChange = info => {
        console.log(info);
        getBase64( info.file, (imageUrl) => {
            console.log("imageUrl", imageUrl)
            this.setState({
                img_url: imageUrl,
                loading: false,
            })
        });
    };

    // 校验能否被解析成 json 对象的验证函数
    myJsonParseValidator = (rule, value, callback) => {
        try {
            let res = JSON.parse(value);
            console.log("NewLogicComponentForm: myJsonParseValidator: 解析结果: ", res)
        }catch (e) {
            callback("解析失败，无法被系统识别！")
        }
        callback()
    }

    // 渲染函数
    render() {
        let { img_url } = this.state;
        const { getFieldDecorator } = this.props.form;
        return <Form onSubmit={this.onClickSubmit}>
            <Form.Item>
                {getFieldDecorator('group_name', {
                    rules: [
                        { required: true, message: '请输入组名（Group Name）！',},
                    ],
                })(<Input placeholder="请输入组名（Group Name）"/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('title', {
                    rules: [
                        { required: true, message: '请输入英文组件名（Title）！',},
                    ],
                })(<Input placeholder="请输入英文组件名（Title）"/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('text_str', {
                    rules: [
                        { required: true, message: '请输入文本标签（Text Str）！',},
                    ],
                })(<Input placeholder="请输入文本标签（Text Str）"/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('type_int', {
                    rules: [
                        { required: true, message: '请输入类型（Type Str），0 代表输入，1 代表运算！',},
                    ],
                })(<InputNumber min={0} max={1} placeholder="请输入类型（Type Str）" style={{ width: "100%" }}/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('input_parameter', {
                    rules: [
                        { required: true, message: '请输入输入参数以及默认值（Input Parameter）！',},
                        { validator: this.myJsonParseValidator }
                    ],
                })(<Input.TextArea placeholder="请输入输入参数以及默认值（Input Parameter）"/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('middle_parameter', {
                    rules: [
                        { required: true, message: '请输入中间参数以及默认值（Middle Parameter）！',},
                        { validator: this.myJsonParseValidator }
                    ],
                })(<Input.TextArea placeholder="请输入中间参数以及默认值（Middle Parameter）"/>)}
            </Form.Item>
            <Form.Item>
                {getFieldDecorator('output_parameter', {
                    rules: [
                        { required: true, message: '请输入输出参数以及默认值（Output Parameter）！',},
                        { validator: this.myJsonParseValidator }
                    ],
                })(<Input.TextArea placeholder="请输入输出参数以及默认值（Output Parameter）"/>)}
            </Form.Item>
            <Upload
                name="logic_component"
                listType="picture-card"
                className="img-uploader"
                showUploadList={false}
                // action={baseUrl + "/logic_component/file"}
                beforeUpload={this.beforeUpload}
                onChange={this.handleChange}
            >
                {img_url!==null ? <img src={img_url} style={{ width: "100%" }}/> : <div>
                    <Icon type="plus" />
                    <div className="ant-upload-text">点击上传</div>
                </div>}
            </Upload>
            <Upload
                name="file"
                action={ baseUrl + "/logic_component/file" }
                accept=".py"
                data={{
                    user_id: this.state.user_id,
                }}
                headers={{
                    authorization: "authorization-text"
                }}
                onChange={(info)=>{
                    if (info.file.status !== 'uploading'){
                        console.log(info.file, info.fileList)
                    }
                    if (info.file.status === 'done'){
                        let { response } = info.file;
                        if (response && response.data){
                            let { file_path } = response.data;
                            this.setState({ file_path }, ()=>{
                                message.success("上传成功: "+file_path)
                            })
                        }
                    }
                    if (info.file.status === 'error'){
                        message.error(info.file.name)
                    }
                }}
            >
                <Button><Icon type="upload"/>点击上传脚本文件</Button>
            </Upload>
            <Form.Item>
                <Button htmlType="submit">提交</Button>
            </Form.Item>
        </Form>
    }
}

export default Form.create()(NewLogicComponentForm);
